package com.lcredu.lcrsnack.commodity.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcredu.common.utils.PageUtils;
import com.lcredu.common.utils.Query;

import com.lcredu.lcrsnack.commodity.dao.CategoryDao;
import com.lcredu.lcrsnack.commodity.entity.CategoryEntity;
import com.lcredu.lcrsnack.commodity.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    //流式计算+递归进行操作
    @Override
    public List<CategoryEntity> listTree() {
        //思路分析-步骤
        //1.查出所有分类数据
        //ServiceImpl自动装配
        List<CategoryEntity> entities = baseMapper.selectList(null);//返回所有数据

        //2. 组装成层级树形结构[stream api + 递归]
        //思路

        List<CategoryEntity> categoryTree = entities.stream().filter(categoryEntity -> {
            //2.1 对entities进行过滤,返回一级分类
            return categoryEntity.getParentId() == 0;
        }).map(category -> {
            //2.2 进行map映射操作，给每个一级分类设置对应的子分类(这个过程会使用到递归)
            category.setChildrenCategories(getChildrenCategories(category, entities));
            return category;
        }).sorted((category1, category2) -> {
            //2.3 进行排序sorted操作,按照升序排列
            return (category1.getSort() == null ? 0 : category1.getSort()) -
                    (category2.getSort() == null ? 0 : category2.getSort());
        }).collect(Collectors.toList());//2.4 将处理好的数据进行一个收集collect到集合中

        //3.返回带层级关系的数据-树形


        return categoryTree;
    }
    //递归查询所有分类的子分类
    //所有子分类的层级关系组织好
    //all就是所有分类信息
    private List<CategoryEntity> getChildrenCategories(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentId() == root.getId();//招一级分类下的子分类
        }).map(categoryEntity -> {
            //1.找到子分类，递归设置
            categoryEntity.setChildrenCategories(getChildrenCategories(categoryEntity, all));
            return categoryEntity;
        }).sorted((category1, category2) -> {
            //按照sort排序,升序
            return (category1.getSort() == null ? 0 : category1.getSort()) - (category2.getSort() == null ? 0 : category2.getSort());
        }).collect(Collectors.toList());

        return children;
    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

}
